package cn.le.netty.messagePack;

import cn.le.bean.util.NettyResponse;
import cn.le.bean.vo.NettyMsg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.msgpack.MessagePack;

import java.util.List;

public class MessagePackDecoder extends MessageToMessageDecoder<ByteBuf> {

    /**
     * 解码来自NettyServer的消息,类型为NettyMsg
     * @param channelHandlerContext
     * @param byteBuf
     * @param list
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int len = byteBuf.readableBytes();//获取可读数据长度
        byte[] data = new byte[len];
        byteBuf.getBytes(byteBuf.readerIndex(),data,0,len);
        MessagePack pack = new MessagePack();
        NettyMsg response = pack.read(data,pack.lookup(NettyMsg.class));
        list.add(response);
    }
}
